const WXAPI = require('../../wxapi/main')
const app = getApp();
const WxParse = require('../../wxParse/wxParse.js');
const regeneratorRuntime = require('../../utils/runtime')

Page({
  data: {
    autoplay: true,
    interval: 3000,
    duration: 1000,
    mygoodsDetail: {},
    swiperCurrent: 0,
    hasMoreSelect: false,
    selectSize: "选择：",
    totalScoreToPay: 0,
    shopNum: 0,
    hideShopPopup: true,
    buyNumber: 1,
    buyNumMin: 1,
    buyNumMax: 0,
    selectSizePrice: 0, // 现价
    pInventory: 0, // 库存数
    pdList: [], // 商品详情的介绍图片
    bannerList: [], // 商品详情轮播图
    pIntro: '', // 商品详细介绍
    pName: '', // 商品名称
    nowPrice: '', //商品现价
    propertyChildIds: "",
    propertyChildNames: "",
    canSubmit: false, //  选中规格尺寸时候是否允许加入购物车
    shopCarInfo: {},
    shopType: "addShopCar", //购物类型，加入购物车或立即购买，默认为加入购物车
    currentPages: undefined,
    aid: [], //规格id
    label: '', //规格
    pIsintegral: '', //积分
    commission: '', //佣金
    discount: '', //折扣
    pjDataList: [],
    pjDataListLength: 0,
    isCollection: 0,
    pSelfhelp: 0,
    OpenId: '',
  },
  onClick(event) {
    var that = this;
    // wx.showToast({
    //   title: `点击标签 ${event.detail.index + 1}`,
    //   icon: 'none'
    // });
    var isClick = `${event.detail.index + 1}`;
    console.log(isClick);
    console.log(typeof(isClick));
    if (isClick == 2) {
      console.log("选中");
      wx.request({
        url: 'https://www.brvpmusic.com/api/userEvaluation/EvaluationList',
        data: {
          'pPid': this.data.mygoodsId
          // 'pPid': 48,
        },
        method: 'GET',
        header: {
          'Content-Type': 'application/json'
        },
        success: function(res) {
          console.log('商品评价获取成功');
          console.log(res.data);
          var result = res.data.body
          console.log("长度:" + result.length);
          var resultLength = result.length;
          that.setData({
            pjDataList: result,
            pjDataListLength: resultLength,
          })
        },
        fail: function(res) {
          console.log('返回失败');
        }
      })
    }
  },
  collect() {
    var that = this;
    wx.request({
      url: 'https://www.brvpmusic.com/api/collect/add',
      // url: 'https://www.brvpmusic.com/api/products/getList',
      data: {
        'cOpenid': wx.getStorageSync('OpenId'),
        'pPid': this.data.mygoodsId
      },
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        that.setData({
          isCollection: 1
        });
        that.onLoad;
      },
      fail: function(res) {
        console.log('返回失败');
      }
    })
  },
  cancelcollect() {
    var that = this;
    wx.request({
      url: 'https://www.brvpmusic.com/api/collect/delete',
      // url: 'https://www.brvpmusic.com/api/products/getList',
      data: {
        'cOpenid': wx.getStorageSync('OpenId'),
        'pPid': this.data.mygoodsId
      },
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        that.setData({
          isCollection: 0
        });
        that.onLoad;
      },
      fail: function(res) {
        console.log('返回失败');
      }
    })
  },
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },

  //事件处理函数
  swiperchange: function(e) {
    //console.log(e.detail.current)
    this.setData({
      swiperCurrent: e.detail.current
    })
  },
  async onLoad(e) {
    this.data.mygoodsId = e.id
    const that = this
    this.data.kjJoinUid = e.kjJoinUid

    // 获取购物车数据
    this.shoppingTrolleyGetList()
    // wx.getStorage({
    //   key: 'shopCarInfo',
    //   success: function(res) {
    //     that.setData({
    //       shopCarInfo: res.data,
    //       shopNum: res.data.shopNum,
    //       curuid: wx.getStorageSync('uid')
    //     });
    //   }
    // })
    this.reputation(e.id)
  },
  // 获取购物车数据
  shoppingTrolleyGetList() {
    var that = this
    wx.request({
      url: 'https://www.brvpmusic.com/api/shoppingTrolley/getList',
      // url: 'https://www.brvpmusic.com/api/products/getList',
      data: {
        'openid': wx.getStorageSync('OpenId')
      },
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        console.log('购物车数据获取成功');
        console.log(res.data);
        var shopNum = 0
        if (res.data.status) {
          var list = res.data.body
          list.forEach(element => {
            shopNum += element.sNum
          });

        }
        that.setData({
          shopNum
        })
      },
      fail: function(res) {
        console.log('返回失败');
      }
    })
  },
  onShow() {
    var that = this;
    wx.showLoading();
    // 商品详情获取
    wx.request({
      // url: 'http://3s.dkys.org:14653/api/products/getProducts',
      url: 'https://www.brvpmusic.com/api/products/getProducts',
      data: {
        'pPid': this.data.mygoodsId,
        'cOpenid': wx.getStorageSync('OpenId')
      },
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        wx.hideLoading()
        console.log('商品详情获取成功');
        console.log(res.data.body);
        var RES = res.data.body;
        that.setData({
          mygoodsDetail: RES,
          bannerList: RES.bannerList,
          selectSizePrice: RES.products.nowPrice,
          pInventory: RES.products.pInventory,
          pdList: RES.pdList,
          pIntro: RES.products.pIntro,
          pName: RES.products.pName,
          nowPrice: RES.products.nowPrice,
          commission: RES.products.commission,
          pIsintegral: RES.products.pIsintegral,
          isCollection: RES.pIscollection,
          pjDataListLength: RES.pjListSize,
          pSelfhelp: RES.products.pSelfhelp
        })
        if (wx.getStorageSync("discount") != null || wx.getStorageSync("discount") != "") {
          that.setData({
            discount: wx.getStorageSync("discount")
          })
        } else {
          that.setData({
            discount: 0
          })
        }
        if (RES.products.specList.length > 0 && RES.products.specList[0].attributeList.length > 0) {
          that.setData({
            hasMoreSelect: true,
            buyNumMax: RES.products.pInventory,
            // selectSize: that.data.selectSize + selectSizeTemp,
            // selectSizePrice: goodsDetailRes.data.basicInfo.minPrice,
            // totalScoreToPay: goodsDetailRes.data.basicInfo.minScore
          });

          let length = RES.products.specList.length
          that.data.aid.length = length
          console.log(that.data.aid, 125);
        }
        var commission = 0;
        if (RES.products.comboTitle == null) {
          commission = RES.products.commission
        } else {
          if (RES.products.comboTitle) {
            let comboTitle = RES.products.comboTitle
            let combo = RES.products.combo.split(',')
            let comboPrice = RES.products.comboPrice.split(',')
            let comboList = []
            if (RES.products.brokerage=='0'){
              commission = 0;
              comboPrice.forEach((element, index) => {
                comboList.push({
                  name: combo[index],
                  index,
                  id: parseFloat(element)
                })
              });
            }else{
              let brokerage = RES.products.brokerage.split(',')
              comboPrice.forEach((element, index) => {
                comboList.push({
                  name: combo[index],
                  index,
                  commission: parseFloat(brokerage[index]),
                  id: parseFloat(element)
                })
              });
            }
            
            that.setData({
              comboListObj: {
                index: 0,
                comboTitle,
                comboList,
              },
              comboSpec: comboTitle + '：' + comboList[0].name,
              comboPrice: comboList[0].id
            })
            console.log(that.data.comboListObj, 221);
            console.log(that.data.buyNumber, 221);
          }
        }


      },
      fail: function(res) {
        wx.hideLoading()
        console.log('返回失败');
      }
    })
    that.getGoodsDetailAndKanjieInfo(that.data.goodsId)
  },
  async getGoodsDetailAndKanjieInfo(goodsId) {
    const that = this;
    const goodsDetailRes = await WXAPI.goodsDetail(goodsId)
    const goodsKanjiaSetRes = await WXAPI.kanjiaSet(goodsId)
    if (goodsDetailRes.code == 0) {
      var selectSizeTemp = "";
      if (goodsDetailRes.data.properties) {
        for (var i = 0; i < goodsDetailRes.data.properties.length; i++) {
          selectSizeTemp = selectSizeTemp + " " + goodsDetailRes.data.properties[i].name;
        }
        that.setData({
          hasMoreSelect: true,
          selectSize: that.data.selectSize + selectSizeTemp,
          selectSizePrice: goodsDetailRes.data.basicInfo.minPrice,
          totalScoreToPay: goodsDetailRes.data.basicInfo.minScore
        });
      }
      if (goodsDetailRes.data.basicInfo.pingtuan) {
        that.pingtuanList(goodsId)
      }
      that.data.goodsDetail = goodsDetailRes.data;
      if (goodsDetailRes.data.basicInfo.videoId) {
        that.getVideoSrc(goodsDetailRes.data.basicInfo.videoId);
      }
      let _data = {
        goodsDetail: goodsDetailRes.data,
        selectSizePrice: goodsDetailRes.data.basicInfo.minPrice,
        totalScoreToPay: goodsDetailRes.data.basicInfo.minScore,
        buyNumMax: goodsDetailRes.data.basicInfo.stores,
        buyNumber: (goodsDetailRes.data.basicInfo.stores > 0) ? 1 : 0,
        currentPages: getCurrentPages()
      }
      if (goodsKanjiaSetRes.code == 0) {
        _data.curGoodsKanjia = goodsKanjiaSetRes.data
        that.data.kjId = goodsKanjiaSetRes.data.id
        // 获取当前砍价进度
        if (!that.data.kjJoinUid) {
          that.data.kjJoinUid = wx.getStorageSync('uid')
        }
        const curKanjiaprogress = await WXAPI.kanjiaDetail(goodsKanjiaSetRes.data.id, that.data.kjJoinUid)
        const myHelpDetail = await WXAPI.kanjiaHelpDetail(goodsKanjiaSetRes.data.id, that.data.kjJoinUid, wx.getStorageSync('token'))
        if (curKanjiaprogress.code == 0) {
          _data.curKanjiaprogress = curKanjiaprogress.data
        }
        if (myHelpDetail.code == 0) {
          _data.myHelpDetail = myHelpDetail.data
        }
      }
      if (goodsDetailRes.data.basicInfo.pingtuan) {
        const pingtuanSetRes = await WXAPI.pingtuanSet(goodsId)
        if (pingtuanSetRes.code == 0) {
          _data.pingtuanSet = pingtuanSetRes.data
        }
      }
      that.setData(_data);
      WxParse.wxParse('article', 'html', goodsDetailRes.data.content, that, 5);
    }
  },
  goShopCar: function() {
    wx.reLaunch({
      url: "/pages/shop-cart/index"
    });
  },
  toAddShopCar: function() {
    this.setData({
      shopType: "addShopCar"
    })
    this.bindGuiGeTap();
  },
  tobuy: function() {
    this.setData({
      shopType: "tobuy",
      selectSizePrice: this.data.mygoodsDetail.products.nowPrice
    });
    this.bindGuiGeTap();
  },
  toPingtuan: function(e) {
    let pingtuanopenid = 0
    if (e.currentTarget.dataset.pingtuanopenid) {
      pingtuanopenid = e.currentTarget.dataset.pingtuanopenid
    }
    this.setData({
      shopType: "toPingtuan",
      selectSizePrice: this.data.goodsDetail.basicInfo.pingtuanPrice,
      pingtuanopenid: pingtuanopenid
    });
    this.bindGuiGeTap();
  },
  /**
   * 规格选择弹出框
   */
  bindGuiGeTap: function() {
    this.setData({
      hideShopPopup: false
    })
  },
  /**
   * 规格选择弹出框隐藏
   */
  closePopupTap: function() {
    this.setData({
      hideShopPopup: true
    })
  },
  numJianTap: function() {
    if (this.data.buyNumber > this.data.buyNumMin) {
      var currentNum = this.data.buyNumber;
      var nowPrice = this.data.nowPrice;
      currentNum--;
      this.setData({
        buyNumber: currentNum,
        selectSizePrice: nowPrice
        //  selectSizePrice: nowPrice * currentNum
      })
    }
  },
  numJiaTap: function(e) {
    console.log(e);
    console.log("buyNumber" + this.data.buyNumber);
    console.log("buyNumMax" + this.data.pInventory);
    if (this.data.buyNumber < this.data.pInventory) {
      var currentNum = this.data.buyNumber;
      var nowPrice = this.data.nowPrice;
      console.log(currentNum);
      currentNum++;
      this.setData({
        buyNumber: currentNum,
        selectSizePrice: nowPrice
        // selectSizePrice: nowPrice * currentNum
      })
    }
  },
  /**
   * 选择商品规格 价格变动
   * @param {Object} e
   */
  labelItemTapcombo(e) {
    var index = e.currentTarget.dataset.propertyindex
    var name = e.currentTarget.dataset.propertyname
    var id = e.currentTarget.dataset.propertyid
    var com= e.currentTarget.dataset.propertycom

    var comboListObj = this.data.comboListObj
    comboListObj.index = index
    this.setData({
      comboListObj,
      comboSpec: comboListObj.comboTitle + '：' + name,
      comboPrice: id,
      commission: com
    })
  },
  /**
   * 选择商品规格
   * @param {Object} e
   */
  labelItemTap: function(e) {
    console.log(e.currentTarget.dataset.propertyitemchild)
    console.log(e.currentTarget.dataset.propertyitem)
    console.log(e.currentTarget.dataset.propertyindexchild)
    console.log(e.currentTarget.dataset.propertyindex)
    var index = e.currentTarget.dataset.propertyindex
    var indexchild = e.currentTarget.dataset.propertyindexchild
    var item = e.currentTarget.dataset.propertyitem
    var itemchild = e.currentTarget.dataset.propertyitemchild
    var specList = this.data.mygoodsDetail.products.specList
    specList[index].checkid = specList[index].attributeList[indexchild].aid
    this.setData({
      'mygoodsDetail.products.specList': specList
    })

    var that = this;
    console.log(e);
    console.log(e.currentTarget.dataset);
    console.log("cehi-:" + e.currentTarget.dataset.propertychildindex);
    var aid = this.data.aid
    aid[index] = specList[index].checkid
    that.setData({
      // 'aid': e.currentTarget.dataset.propertyindex,
      'aid': aid,
      'label': e.currentTarget.dataset.propertyname + ':' + e.currentTarget.dataset.propertychildname,
      'cindex': e.currentTarget.dataset.propertychildindex,
    })
    console.log(this.data.aid, 289);
    wx.showToast({
      title: '您选择了' + e.currentTarget.dataset.propertychildname,
    })


    // // 取消该分类下的子栏目所有的选中状态
    // var childs = that.data.goodsDetail.properties[e.currentTarget.dataset.propertyindex].childsCurGoods;
    // for (var i = 0; i < childs.length; i++) {
    //   that.data.goodsDetail.properties[e.currentTarget.dataset.propertyindex].childsCurGoods[i].active = false;
    // }
    // // 设置当前选中状态
    // that.data.goodsDetail.properties[e.currentTarget.dataset.propertyindex].childsCurGoods[e.currentTarget.dataset.propertychildindex].active = true;
    // // 获取所有的选中规格尺寸数据
    // var needSelectNum = that.data.goodsDetail.properties.length;
    // var curSelectNum = 0;
    // var propertyChildIds = "";
    // var propertyChildNames = "";
    // for (var i = 0; i < that.data.goodsDetail.properties.length; i++) {
    //   childs = that.data.goodsDetail.properties[i].childsCurGoods;
    //   for (var j = 0; j < childs.length; j++) {
    //     if (childs[j].active) {
    //       curSelectNum++;
    //       propertyChildIds = propertyChildIds + that.data.goodsDetail.properties[i].id + ":" + childs[j].id + ",";
    //       propertyChildNames = propertyChildNames + that.data.goodsDetail.properties[i].name + ":" + childs[j].name + "  ";
    //     }
    //   }
    // }
    // var canSubmit = false;
    // if (needSelectNum == curSelectNum) {
    //   canSubmit = true;
    // }
    // // 计算当前价格
    // if (canSubmit) {
    //   WXAPI.goodsPrice({
    //     goodsId: that.data.goodsDetail.basicInfo.id,
    //     propertyChildIds: propertyChildIds
    //   }).then(function(res) {
    //     that.setData({
    //       selectSizePrice: res.data.price,
    //       totalScoreToPay: res.data.score,
    //       propertyChildIds: propertyChildIds,
    //       propertyChildNames: propertyChildNames,
    //       buyNumMax: res.data.stores,
    //       buyNumber: (res.data.stores > 0) ? 1 : 0
    //     });
    //   })
    // }


    // this.setData({
    //   goodsDetail: that.data.goodsDetail,
    //   canSubmit: canSubmit
    // })
  },
  /**
   * 加入购物车
   */
  addShopCar: function() {
    // if (this.data.goodsDetail.properties && !this.data.canSubmit) {
    //   if (!this.data.canSubmit) {
    //     wx.showModal({
    //       title: '提示',
    //       content: '请选择商品规格！',
    //       showCancel: false
    //     })
    //   }
    //   this.bindGuiGeTap();
    //   return;
    // }
    let that = this
    // if (this.data.goodsDetail.properties && !this.data.canSubmit) {
    //   if (!this.data.canSubmit) {
    //     wx.showModal({
    //       title: '提示',
    //       content: '请选择商品规格！',
    //       showCancel: false
    //     })
    //   }
    //   this.bindGuiGeTap();
    //   wx.showModal({
    //     title: '提示',
    //     content: '请先选择规格尺寸哦~',
    //     showCancel: false
    //   })
    //   return;
    // }
    console.log("this.data.pInventory" + this.data.pInventory);
    if (this.data.buyNumber < 1) {
      wx.showModal({
        title: '提示',
        content: '购买数量不能为0！',
        showCancel: false
      })
      return;
    } else if (this.data.buyNumber > 5) {
      wx.showToast({
        title: '超出购买数量！',
      })
      return;
    } else {
      if (this.data.pInventory - this.data.buyNumber < 0) {
        wx.showToast({
          title: '您购买的商品库存不足！',
        })
        return;
      }
    }
    console.log(this.data.mygoodsDetail.products.specList, 457)
    console.log(this.data.aid, 457)
    if (this.data.mygoodsDetail.products.specList.length > 0) {
      // var checkEmpty = this.data.aid.filter(element => {
      //     return element === undefined
      // });
      var lengthaidundefined = 0
      console.log(472)
      for (let index = 0; index < this.data.aid.length; index++) {
        const element = this.data.aid[index];
        if (element === undefined) {
          lengthaidundefined++
        }
      }
      console.log(lengthaidundefined, 461)
      if (lengthaidundefined > 0) {
        wx.showModal({
          title: '提示',
          content: '请选择规格',
          showCancel: false
        })
        return;
      }
    }
    // that.setData({
    //     comboListObj: {
    //         index: 0,
    //         comboTitle,
    //         comboList,
    //     },
    //     comboSpec: comboTitle + '：' + comboList[0].name,
    //     comboPrice: comboList[0].id
    // })

    var aid = this.data.aid;
    var params = {
      'openid': wx.getStorageSync('OpenId'),
      'products': this.data.mygoodsDetail.products.pPid,
      'sNum': this.data.buyNumber,
      aid,
    }
    if (this.data.comboPrice) {
      params.price = this.data.comboPrice
    }
    if (this.data.comboSpec) {
      params.spec = this.data.comboSpec
    }
    if (this.data.commission) {
      params.brokerage = this.data.commission
    }
    console.log(params)
    wx.showLoading()
    // 加入购物车
    wx.request({
      // url: 'http://3s.dkys.org:25333/api/shoppingTrolley/addShoppingTrolley',
      url: 'https://www.brvpmusic.com/api/shoppingTrolley/addShoppingTrolley',
      // url: con.index_mybanners,
      data: params,
      method: 'POST',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        wx.hideLoading()
        console.log('返回成功');
        console.log(res.data);
        if (res.data.status) {
          that.closePopupTap();
          wx.showToast({
            title: '加入购物车成功',
            icon: 'success',
            duration: 2000
          })
          that.shoppingTrolleyGetList()
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none'
          })
        }
        // that.setData({
        //   mybanners: res.data.data,
        // })
      },
      fail: function(res) {
        wx.hideLoading()
        console.log('返回失败');
      }
    })

    //组建购物车
    // var shopCarInfo = this.bulidShopCarInfo();

    // this.setData({
    //   shopCarInfo: shopCarInfo,
    //   shopNum: shopCarInfo.shopNum
    // });

    // // 写入本地存储
    // wx.setStorage({
    //   key: 'shopCarInfo',
    //   data: shopCarInfo
    // })
    // this.closePopupTap();
    // wx.showToast({
    //   title: '加入购物车成功',
    //   icon: 'success',
    //   duration: 2000
    // })
    // console.log(shopCarInfo);

    // shopCarInfo = {
    //   shopNum: 12,
    //   shopList: []
    // }
  },
  /**
   * 立即购买
   */
  buyNow: function(e) {
    let that = this
    let shoptype = e.currentTarget.dataset.shoptype;
    let OpenId = wx.getStorageSync('OpenId');
    console.log(shoptype)
    // if (this.data.goodsDetail.properties && !this.data.canSubmit) {
    //   if (!this.data.canSubmit) {
    //     wx.showModal({
    //       title: '提示',
    //       content: '请选择商品规格！',
    //       showCancel: false
    //     })
    //   }
    //   this.bindGuiGeTap();
    //   wx.showModal({
    //     title: '提示',
    //     content: '请先选择规格尺寸哦~',
    //     showCancel: false
    //   })
    //   return;
    // }
    console.log("this.data.pInventory" + this.data.pInventory);
    if (this.data.buyNumber < 1) {
      wx.showModal({
        title: '提示',
        content: '购买数量不能为0！',
        showCancel: false
      })
      return;
    } else if (this.data.buyNumber > 5) {
      wx.showToast({
        title: '超出购买数量！',
      })
      return;
    } else {
      if (this.data.pInventory - this.data.buyNumber < 0) {
        wx.showToast({
          title: '您购买的商品库存不足！',
        })
        return;
      }
    }
    console.log(this.data.mygoodsDetail.products.specList, 457)
    console.log(this.data.aid, 457)
    if (this.data.mygoodsDetail.products.specList.length > 0) {
      // var checkEmpty = this.data.aid.filter(element => {
      //     return element === undefined
      // });
      var lengthaidundefined = 0
      console.log(472)
      for (let index = 0; index < this.data.aid.length; index++) {
        const element = this.data.aid[index];
        if (element === undefined) {
          lengthaidundefined++
        }
      }
      console.log(lengthaidundefined, 461)
      if (lengthaidundefined > 0) {
        wx.showModal({
          title: '提示',
          content: '请选择规格',
          showCancel: false
        })
        return;
      }
    }
    //组建立即购买信息
    var buyNowInfo = this.buliduBuyNowInfo(shoptype);
    var pPostage = that.data.mygoodsDetail.products.pPostage;
    var pSelfhelp = that.data.mygoodsDetail.products.pSelfhelp;
    var brokerage = that.data.commission;
    console.log("pPostage--brokerage--" + pPostage + "---" + brokerage);
    // 写入本地存储
    wx.setStorage({
      key: "buyNowInfo",
      data: buyNowInfo
    })
    this.closePopupTap();
    if (shoptype == 'toPingtuan') {
      if (this.data.pingtuanopenid) {
        wx.navigateTo({
          url: '/pages/to-pay-order/index?orderType=buyNow&pingtuanOpenId=' + this.data.pingtuanopenid
        })
      }
      // else {
      //   WXAPI.pingtuanOpen(that.data.goodsDetail.basicInfo.id, wx.getStorageSync('token')).then(function(res) {
      //     if (res.code != 0) {
      //       wx.showToast({
      //         title: res.msg,
      //         icon: 'none',
      //         duration: 2000
      //       })
      //       return
      //     }
      //     wx.navigateTo({
      //       url: "/pages/to-pay-order/index?orderType=buyNow&pingtuanOpenId=" + res.data.id
      //     })
      //   })
      // }
    } else {
      if (OpenId != '' && OpenId != 'undefined') {
        wx.navigateTo({
          url: '/pages/to-pay-order/index?orderType=buyNow&pPostage=' + pPostage + '&pSelfhelp=' + pSelfhelp + '&brokerage=' + brokerage
        });
      } else {
        wx.navigateTo({
          url: "/pages/authorize/index"
        });
      }
    }

  },
  /**
   * 组建购物车信息
   */
  bulidShopCarInfo: function() {
    // 加入购物车
    var shopCarMap = {};
    shopCarMap.goodsId = this.data.mygoodsDetail.products.pPid;
    shopCarMap.pic = 'https://www.brvpmusic.com' + this.data.mygoodsDetail.products.pictureStorages[0].pImgurl;
    shopCarMap.name = this.data.mygoodsDetail.products.pName;
    // shopCarMap.label=this.data.mygoodsDetail.products.id; 规格尺寸 
    shopCarMap.propertyChildIds = this.data.aid;
    shopCarMap.label = this.data.label;
    shopCarMap.price = this.data.selectSizePrice;
    shopCarMap.score = this.data.totalScoreToPay;
    shopCarMap.commission = this.data.commission;
    shopCarMap.pIsintegral = this.data.pIsintegral;
    shopCarMap.left = "";
    shopCarMap.active = true;
    shopCarMap.number = this.data.buyNumber;
    // shopCarMap.logisticsType = this.data.goodsDetail.basicInfo.logisticsId;
    // shopCarMap.logistics = this.data.goodsDetail.logistics;
    // shopCarMap.weight = this.data.goodsDetail.basicInfo.weight;

    var shopCarInfo = this.data.shopCarInfo;
    if (!shopCarInfo.shopNum) {
      shopCarInfo.shopNum = 0;
    }
    if (!shopCarInfo.shopList) {
      shopCarInfo.shopList = [];
    }
    var hasSameGoodsIndex = -1;
    for (var i = 0; i < shopCarInfo.shopList.length; i++) {
      var tmpShopCarMap = shopCarInfo.shopList[i];
      if (tmpShopCarMap.goodsId == shopCarMap.goodsId && tmpShopCarMap.propertyChildIds == shopCarMap.propertyChildIds) {
        hasSameGoodsIndex = i;
        shopCarMap.number = shopCarMap.number + tmpShopCarMap.number;
        break;
      }
    }

    shopCarInfo.shopNum = shopCarInfo.shopNum + this.data.buyNumber;
    if (hasSameGoodsIndex > -1) {
      shopCarInfo.shopList.splice(hasSameGoodsIndex, 1, shopCarMap);
    } else {
      shopCarInfo.shopList.push(shopCarMap);
    }
    shopCarInfo.kjId = this.data.kjId;
    return shopCarInfo;
  },
  /**
   * 组建立即购买信息
   */
  buliduBuyNowInfo: function(shoptype) {
    var shopCarMap = {};
    shopCarMap.goodsId = this.data.mygoodsDetail.products.pPid;
    shopCarMap.pic = 'https://www.brvpmusic.com' + this.data.mygoodsDetail.products.pictureStorages[0].pImgurl;
    shopCarMap.name = this.data.mygoodsDetail.products.pName;
    // shopCarMap.label=this.data.mygoodsDetail.products.id; 规格尺寸 
    shopCarMap.propertyChildIds = this.data.aid;
    shopCarMap.label = this.data.label;
    if (this.data.comboPrice) {
      shopCarMap.comboPrice = this.data.comboPrice;
    }
    if (this.data.comboSpec) {
      shopCarMap.comboSpec = this.data.comboSpec;
    }

    shopCarMap.price = this.data.selectSizePrice;
    shopCarMap.score = this.data.totalScoreToPay;
    shopCarMap.commission = this.data.commission;
    shopCarMap.pIsintegral = this.data.pIsintegral;
    shopCarMap.left = "";
    shopCarMap.active = true;
    shopCarMap.number = this.data.buyNumber;
    // shopCarMap.logisticsType = this.data.goodsDetail.basicInfo.logisticsId;
    // shopCarMap.logistics = this.data.goodsDetail.logistics;
    // shopCarMap.weight = this.data.goodsDetail.basicInfo.weight;
    // var shopCarMap = {};
    // shopCarMap.goodsId = this.data.goodsDetail.basicInfo.id;
    // shopCarMap.pic = this.data.goodsDetail.basicInfo.pic;
    // shopCarMap.name = this.data.goodsDetail.basicInfo.name;
    // // shopCarMap.label=this.data.goodsDetail.basicInfo.id; 规格尺寸 
    // shopCarMap.propertyChildIds = this.data.propertyChildIds;
    // shopCarMap.label = this.data.propertyChildNames;
    // shopCarMap.price = this.data.selectSizePrice;
    // if (shoptype == 'toPingtuan') {
    //   shopCarMap.price = this.data.goodsDetail.basicInfo.pingtuanPrice;
    // }
    // shopCarMap.score = this.data.totalScoreToPay;
    // shopCarMap.left = "";
    // shopCarMap.active = true;
    // shopCarMap.number = this.data.buyNumber;
    // shopCarMap.logisticsType = this.data.goodsDetail.basicInfo.logisticsId;
    // shopCarMap.logistics = this.data.goodsDetail.logistics;
    // shopCarMap.weight = this.data.goodsDetail.basicInfo.weight;

    var buyNowInfo = {};
    if (!buyNowInfo.shopNum) {
      buyNowInfo.shopNum = 0;
    }
    if (!buyNowInfo.shopList) {
      buyNowInfo.shopList = [];
    }
    /*    var hasSameGoodsIndex = -1;
        for (var i = 0; i < toBuyInfo.shopList.length; i++) {
          var tmpShopCarMap = toBuyInfo.shopList[i];
          if (tmpShopCarMap.goodsId == shopCarMap.goodsId && tmpShopCarMap.propertyChildIds == shopCarMap.propertyChildIds) {
            hasSameGoodsIndex = i;
            shopCarMap.number = shopCarMap.number + tmpShopCarMap.number;
            break;
          }
        }
        toBuyInfo.shopNum = toBuyInfo.shopNum + this.data.buyNumber;
        if (hasSameGoodsIndex > -1) {
          toBuyInfo.shopList.splice(hasSameGoodsIndex, 1, shopCarMap);
        } else {
          toBuyInfo.shopList.push(shopCarMap);
        }*/

    buyNowInfo.shopList.push(shopCarMap);
    buyNowInfo.kjId = this.data.kjId;
    return buyNowInfo;
  },
  onShareAppMessage: function() {
    let _data = {
      title: this.data.goodsDetail.basicInfo.name,
      path: '/pages/goods-details/index?id=' + this.data.goodsDetail.basicInfo.id + '&inviter_id=' + wx.getStorageSync('uid'),
      success: function(res) {
        // 转发成功
      },
      fail: function(res) {
        // 转发失败
      }
    }
    if (this.data.kjJoinUid) {
      _data.title = this.data.curKanjiaprogress.joiner.nick + '邀请您帮TA砍价'
      _data.path += '&kjJoinUid=' + this.data.kjJoinUid
    }
    return _data
  },
  reputation: function(goodsId) {
    var that = this;
    WXAPI.goodsReputation({
      goodsId: goodsId
    }).then(function(res) {
      if (res.code == 0) {
        that.setData({
          reputation: res.data
        });
      }
    })
  },
  pingtuanList: function(goodsId) {
    var that = this;
    WXAPI.pingtuanList(goodsId).then(function(res) {
      if (res.code == 0) {
        that.setData({
          pingtuanList: res.data
        });
      }
    })
  },
  getVideoSrc: function(videoId) {
    var that = this;
    WXAPI.videoDetail(videoId).then(function(res) {
      if (res.code == 0) {
        that.setData({
          videoMp4Src: res.data.fdMp4
        });
      }
    })
  },
  // joinKanjia: function() { // 报名参加砍价活动
  //   const _this = this;
  //   if (!_this.data.curGoodsKanjia) {
  //     return;
  //   }
  //   wx.showLoading({
  //     title: '加载中',
  //     mask: true
  //   })
  //   WXAPI.kanjiaJoin(_this.data.curGoodsKanjia.id, wx.getStorageSync('token')).then(function(res) {
  //     wx.hideLoading()
  //     if (res.code == 0) {
  //       _this.data.kjJoinUid = wx.getStorageSync('uid')
  //       _this.getGoodsDetailAndKanjieInfo(_this.data.goodsDetail.basicInfo.id)
  //     } else {
  //       wx.showToast({
  //         title: res.msg,
  //         icon: 'none'
  //       })
  //     }
  //   })
  // },
  joinPingtuan: function(e) {
    let pingtuanopenid = e.currentTarget.dataset.pingtuanopenid
    wx.navigateTo({
      url: "/pages/to-pay-order/index?orderType=buyNow&pingtuanOpenId=" + pingtuanopenid
    })
  },
  goIndex() {
    wx.switchTab({
      url: '/pages/index/index',
    });
  },
  // helpKanjia() {
  //   const _this = this;
  //   WXAPI.kanjiaHelp(_this.data.kjId, _this.data.kjJoinUid, wx.getStorageSync('token'), '').then(function (res) {
  //     if (res.code != 0) {
  //       wx.showToast({
  //         title: res.msg,
  //         icon: 'none'
  //       })
  //       return;
  //     }
  //     _this.setData({
  //       myHelpDetail: res.data
  //     });
  //     wx.showModal({
  //       title: '成功',
  //       content: '成功帮TA砍掉 ' + res.data.cutPrice + ' 元',
  //       showCancel: false
  //     })
  //     _this.getGoodsDetailAndKanjieInfo(_this.data.goodsDetail.basicInfo.id)
  //   })
  // },
})